package com.shuaiche.yeguan.ui.report;

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.shuaiche.yeguan.R;
import com.shuaiche.yeguan.config.HttpUrl;
import com.shuaiche.yeguan.config.SCAppConfig;
import com.shuaiche.yeguan.model.SCAccessAuthResponse;
import com.shuaiche.yeguan.net.http.HttpCallBack;
import com.shuaiche.yeguan.net.http.HttpHelper;
import com.shuaiche.yeguan.net.oss.MultiImagesUploadManager;
import com.shuaiche.yeguan.ui.common.PdfPreviewActivity;
import com.shuaiche.yeguan.util.FileUtils;
import com.shuaiche.yeguan.util.StringUtils;
import com.shuaiche.yeguan.util.ToastShowUtils;
import com.shuaiche.yeguan.util.permission.MPermission;
import com.shuaiche.yeguan.util.permission.OnMPermissionDenied;
import com.shuaiche.yeguan.util.permission.OnMPermissionGranted;
import com.shuaiche.yeguan.util.permission.OnMPermissionNeverAskAgain;
import com.shuaiche.yeguan.views.SCClearEditText;
import com.shuaiche.yeguan.views.SCDragGridView;
import com.shuaiche.yeguan.views.dialog.PermissionDialog;
import com.shuaiche.yeguan.views.photopicker.PhotoPickerActivity;
import com.shuaiche.yeguan.views.photopicker.PhotoPreviewActivity;
import com.shuaiche.yeguan.views.photopicker.SelectModel;
import com.shuaiche.yeguan.views.photopicker.intent.PhotoPickerIntent;
import com.shuaiche.yeguan.views.photopicker.intent.PhotoPreviewIntent;

import java.io.File;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

public class UploadDetectionActivity extends AppCompatActivity implements View.OnClickListener {

    private static final int BASIC_PERMISSION_REQUEST_CODE_FOR_CAMERA = 102;
    private static final int BASIC_PERMISSION_REQUEST_CODE_FOR_FILE = 106;
    private static final int REQUEST_CODE_CAMERA = 103; //选择图片
    private static final int REQUEST_CODE_PREVIEW = 104;    //预览图片
    private static final int REQUEST_CODE_FILE = 105;
    private ArrayList<String> carPictures = new ArrayList<>();  //保存网络图片地址
    private ArrayList<String> carUrlPictures = new ArrayList<>();  //保存本地图片地址
    private final String[] BASIC_PERMISSIONS = new String[]{
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
    };

    private final String[] BASIC_PERMISSIONS_FILE = new String[]{
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
    };

    /**
     * 维保记录
     */
    private String reportPcUrl; //检测报告地址
    private String detectionReportPic;  //检测报告图片
    private ArrayList<String> reportPics = new ArrayList<>();   //图片

    private RelativeLayout rl_back;
    /**
     * 维保url
     */
    TextView tvUrlTitle;
    SCClearEditText etMaintenanceUrl;
    /**
     * 维保报告截图
     */
    TextView tvPicTitle;
    SCDragGridView gvPics;
    LinearLayout uploadPDF;
    ImageView uploadSignIcon;
    TextView tvPdfName;
    TextView tvDelete;


    /**
     * PDF
     */
    RadioButton rbPDF;
    View pdfLine;
    /**
     * 第三方链接
     */
    RadioButton rbThirdLink;
    View thirdLinkLine;
    /**
     * 报告截图
     */
    RadioButton rbReportPics;
    View reportPicsLine;

    RadioGroup rgGroup;

    LinearLayout llPDF;
    LinearLayout llThirdLink;
    LinearLayout llReportPics;

    Button btnConfirm;

    private int uploadType;//0图片 1PDF
    private String detectionReportPdf;
    private ArrayList<String> pdfPaths = new ArrayList<>();

    private String pdfFileName;
    private String localPdfPath;
    private Uri localPdfUri;

    /**
     * 选择的图片下标
     */
    private int picIndex;
    private int maxSize = 30;

    private StringBuffer urlSB = new StringBuffer();
    private StringBuffer urlAll;

    private Handler mainHandler = new Handler(Looper.getMainLooper());

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Window window = getWindow();

        window.getDecorView().setSystemUiVisibility(
               View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
        );

        setContentView(R.layout.activity_upload_detection);

        initViews();
    }

    private void initViews() {
        rl_back = findViewById(R.id.rl_back);
        tvUrlTitle = findViewById(R.id.tvUrlTitle);
        etMaintenanceUrl = findViewById(R.id.etMaintenanceUrl);
        tvPicTitle = findViewById(R.id.tvPicTitle);
        gvPics = findViewById(R.id.gvPics);
        uploadPDF = findViewById(R.id.btn_upload_pdf);
        uploadSignIcon = findViewById(R.id.sign_pdf);
        tvPdfName = findViewById(R.id.tv_pdf_name);
        tvDelete = findViewById(R.id.tv_pdf_delete);
        rbPDF = findViewById(R.id.rb_pdf);
        pdfLine = findViewById(R.id.pdf_line);
        rbThirdLink = findViewById(R.id.rb_third_link);
        thirdLinkLine = findViewById(R.id.third_link_line);
        rbReportPics = findViewById(R.id.rb_report_pics);
        reportPicsLine = findViewById(R.id.report_pics_line);
        rgGroup = findViewById(R.id.rg_group);
        llPDF = findViewById(R.id.ll_pdf);
        llThirdLink = findViewById(R.id.ll_third_link);
        llReportPics = findViewById(R.id.ll_report_pics);
        btnConfirm = findViewById(R.id.btnConfirm);

        rl_back.setOnClickListener(this);
        uploadPDF.setOnClickListener(this);
        rbPDF.setOnClickListener(this);
        rbThirdLink.setOnClickListener(this);
        rbReportPics.setOnClickListener(this);
        tvDelete.setOnClickListener(this);
        btnConfirm.setOnClickListener(this);

        getData();
        gvPics.setSelector(new ColorDrawable(Color.TRANSPARENT));
        gvPics.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                picIndex = position;
                if (ContextCompat.checkSelfPermission(UploadDetectionActivity.this,Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

                    PermissionDialog dialog = new PermissionDialog(UploadDetectionActivity.this,"申请文件读写存储权限","申请文件读写存储权限，用于选择上传媒体图片");
                    dialog.setOnPermissionResultListener(new PermissionDialog.OnPermissionResultListener() {
                        @Override
                        public void onConfirm() {
                            MPermission.with(UploadDetectionActivity.this)
                                    .setRequestCode(BASIC_PERMISSION_REQUEST_CODE_FOR_CAMERA)
                                    .permissions(BASIC_PERMISSIONS)
                                    .request();
                        }

                        @Override
                        public void onRefuse() {

                        }
                    });
                    dialog.setCancelable(false);
                    dialog.show();

                }else {
                    permissionGranted();
                }

            }
        });
        urlAll = new StringBuffer();

        if (!StringUtils.isEmpty(detectionReportPic)) {
            urlAll.append(detectionReportPic);
            String[] pics = detectionReportPic.split(",", -1);
            for (String pic : pics) {
                carPictures.add(SCAppConfig.IMG_URL + pic);
            }
        }
        etMaintenanceUrl.setText(reportPcUrl);
        tvPicTitle.setText("检测报告截图");
        tvUrlTitle.setText("第三方链接");
        etMaintenanceUrl.setHint("请输入车辆检测报告链接");
        loadAdapter();

        if (!StringUtils.isEmpty(detectionReportPdf)) {
            setHasPDFDataView(detectionReportPdf);
        }

    }
    private void getData() {
        if (getIntent() != null) {
            reportPcUrl = getIntent().getStringExtra("detectionReportUrl");
            detectionReportPic = getIntent().getStringExtra("detectionReportPic");
            detectionReportPdf = getIntent().getStringExtra("detectionReportPdf");
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rl_back:
                finish();
                    break;
            case R.id.btnConfirm:
                //上传图片
                reportPcUrl = etMaintenanceUrl.getText().toString();
                if (!StringUtils.isEmpty(reportPcUrl) && !reportPcUrl.startsWith("http")) {
                    reportPcUrl = "https://" + reportPcUrl;
                }

                boolean hasFilledPDF = false;
                if (localPdfUri != null){
                    hasFilledPDF = true;
                } else if (!StringUtils.isEmpty(detectionReportPdf)) {
                    hasFilledPDF = true;
                } else {
                    hasFilledPDF = false;
                }

                if (!hasFilledPDF && StringUtils.isEmpty(reportPcUrl) && (carPictures == null || carPictures.size() == 0)) {
                    ToastShowUtils.showTipToast("请上传PDF文件或车辆检测报告链接或者截图");
                } else {
                    // 上传之间判断url是否填写正确
                    if (!StringUtils.isEmpty(reportPcUrl)) {
                        checkUrlValid();
                    } else {
                        uploadPicsAndPDF();
                    }

                }
                break;
            case R.id.btn_upload_pdf:
                if (ContextCompat.checkSelfPermission(this,Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    PermissionDialog dialog = new PermissionDialog(this,"申请文件读写存储权限","申请文件读写存储权限，用于选择上传pdf文件");
                    dialog.setOnPermissionResultListener(new PermissionDialog.OnPermissionResultListener() {
                        @Override
                        public void onConfirm() {
                            MPermission.with(UploadDetectionActivity.this)
                                    .setRequestCode(BASIC_PERMISSION_REQUEST_CODE_FOR_FILE)
                                    .permissions(BASIC_PERMISSIONS_FILE)
                                    .request();
                        }

                        @Override
                        public void onRefuse() {

                        }
                    });
                    dialog.setCancelable(false);
                    dialog.show();


                }else {
                    gotoSelectFile();
                }

                break;
            case R.id.tv_pdf_delete:
                tvDelete.setText("仅支持PDF文件");
                tvPdfName.setText("点击上传文件");
                uploadSignIcon.setImageResource(R.mipmap.pic_unupload_pdf);
                localPdfPath = "";
                localPdfUri = null;
                detectionReportPdf = "";
                pdfFileName = "";
                if (pdfPaths != null && pdfPaths.size() > 0) {
                    pdfPaths.clear();
                }
                break;
            case R.id.rb_pdf:
                rbPDF.setChecked(true);
                rbThirdLink.setChecked(false);
                rbReportPics.setChecked(false);
                rbThirdLink.setTextColor(getResources().getColor(R.color.color_999999));
                rbReportPics.setTextColor(getResources().getColor(R.color.color_999999));
                pdfLine.setVisibility(View.VISIBLE);
                thirdLinkLine.setVisibility(View.GONE);
                reportPicsLine.setVisibility(View.GONE);
                llPDF.setVisibility(View.VISIBLE);
                llThirdLink.setVisibility(View.GONE);
                llReportPics.setVisibility(View.GONE);
                break;
            case R.id.rb_third_link:
                clickUrlRadio();
                break;
            case R.id.rb_report_pics:
                rbPDF.setChecked(false);
                rbThirdLink.setChecked(false);
                rbReportPics.setChecked(true);
                rbThirdLink.setTextColor(getResources().getColor(R.color.color_999999));
                rbPDF.setTextColor(getResources().getColor(R.color.color_999999));
                pdfLine.setVisibility(View.GONE);
                thirdLinkLine.setVisibility(View.GONE);
                reportPicsLine.setVisibility(View.VISIBLE);
                llPDF.setVisibility(View.GONE);
                llThirdLink.setVisibility(View.GONE);
                llReportPics.setVisibility(View.VISIBLE);
                break;

        }
    }

    private void clickUrlRadio(){
        rbPDF.setChecked(false);
        rbThirdLink.setChecked(true);
        rbReportPics.setChecked(false);
        rbPDF.setTextColor(getResources().getColor(R.color.color_999999));
        rbReportPics.setTextColor(getResources().getColor(R.color.color_999999));
        pdfLine.setVisibility(View.GONE);
        thirdLinkLine.setVisibility(View.VISIBLE);
        reportPicsLine.setVisibility(View.GONE);
        llPDF.setVisibility(View.GONE);
        llThirdLink.setVisibility(View.VISIBLE);
        llReportPics.setVisibility(View.GONE);
    }

    private void uploadPicsAndPDF(){
        if (carPictures != null && carPictures.size() > 0) {
            for (int i = 0; i < carPictures.size(); i++) {
                if (carPictures.get(i).contains(SCAppConfig.IMG_URL)) {
                    urlSB.append(carPictures.get(i).replace(SCAppConfig.IMG_URL, "")).append(",");
                } else {
                    carUrlPictures.add(carPictures.get(i));
                }
            }
            if (carUrlPictures.size() > 0) {
                uploadType = 0;

                HttpHelper.getInstance().appendUrl(HttpUrl.OSS_AUTH)
                        .get(new HttpCallBack<SCAccessAuthResponse>(this) {
                            @Override
                            public void onSuccessed(SCAccessAuthResponse result) {
                                SCAccessAuthResponse auth = result.getData();
                                if (proDialog == null) {
                                    proDialog = new ProgressDialog(UploadDetectionActivity.this);
                                    proDialog.setMessage("正在上传报告");
                                    proDialog.setCanceledOnTouchOutside(false);
                                }
                                proDialog.show();

                                MultiImagesUploadManager.MultiImagesUploadCallback callback =
                                        new MultiImagesUploadManager.MultiImagesUploadCallback() {
                                            @Override
                                            public void onSuccess(List<PutObjectRequest> requests) {
                                                if (requests != null && requests.size() > 0) {
//                                                        if (uploadType == 0) {
                                                    urlSB = new StringBuffer();
                                                    int postion = 0;
                                                    for (int i = 0; i < carPictures.size(); i++) {
                                                        if (carPictures.get(i).contains(SCAppConfig.IMG_URL)) {
                                                            urlSB.append(carPictures.get(i).replace(SCAppConfig.IMG_URL, "")).append(",");
                                                        } else {
                                                            urlSB.append("/" + requests.get(postion++).getObjectKey()).append(",");
                                                        }
                                                    }

                                                    if (urlSB.length() > 0) {
                                                        urlSB.deleteCharAt(urlSB.length() - 1);
                                                    }
                                                    if (urlSB != null) {
                                                        urlAll.append(urlSB);
                                                    }
                                                    proDialog.dismiss();
                                                    if (localPdfUri != null) {
                                                        checkFileAndUpload();
                                                    } else {
                                                        uploadMaintenanceReport();
                                                        ToastShowUtils.showSuccessToast("上传成功");
                                                    }
                                                }


                                            }

                                            @Override
                                            public void onFailure(List<PutObjectRequest> requests) {
                                                ToastShowUtils.showFailedToast("上传失败");
                                                proDialog.dismiss();
                                            }
                                        };

                                if (uploadType == 0) {
                                    new MultiImagesUploadManager().startUploadNoCompress(carUrlPictures, callback,
                                            auth.getAccessKeyId(), auth.getAccessKeySecret(), auth.getSecurityToken(),
                                            SCAppConfig.OSS_CAR);
                                }
                            }

                            @Override
                            public void onFailured(String errorCode, String errMsg) {
                                ToastShowUtils.showFailedToast(errMsg);
                            }
                        });


            } else {
                urlSB.deleteCharAt(urlSB.length() - 1);
                if (localPdfUri != null) {
                    checkFileAndUpload();
                } else {
                    uploadMaintenanceReport();
                }
            }
        } else if (localPdfUri != null){
            checkFileAndUpload();
        } else {
            uploadMaintenanceReport();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);
        //获取本地图片返回
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == REQUEST_CODE_CAMERA) {
                if (carPictures != null && carPictures.size() > 0) {
                    carPictures.clear();
                }
                carPictures = data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT);
                loadAdapter();
            } else if (requestCode == REQUEST_CODE_PREVIEW) {
                if (carPictures != null && carPictures.size() > 0) {
                    carPictures.clear();
                }
                carPictures = data.getStringArrayListExtra(PhotoPreviewActivity.EXTRA_RESULT);
                loadAdapter();
            } else if (requestCode == REQUEST_CODE_FILE) {
                Uri uri = data.getData();
                localPdfUri = uri;
//                Log.e("chj","uri = " + uri);
//                if ("file".equalsIgnoreCase(uri.getScheme())) {//使用第三方应用打开
//                    String path = uri.getPath();
//                    showViewByGetPath(path);
//                    Log.e("chj", "获得地址1" + path);
//                    return;
//                }
//                if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {//4.4以后
//                    String path = FileUtils.getPath(this, uri);
//                    Log.e("chj", "获得地址2" + path);
//                    showViewByGetPath(path);
//                } else {//4.4以下下系统调用方法
//                    String path = FileUtils.getRealPathFromURI(uri, this);
//                    Log.e("chj", "获得地址3" + path);
//                    showViewByGetPath(path);
//                }
                if (uri != null){
                    String fileNameWithEnd = FileUtils.getFileNameByUri(this,uri);
                    showViewByGetPath(fileNameWithEnd);
                }else {
                    ToastShowUtils.showFailedToast("请选择PDF文件上传！");
                }
            }
        }
    }

    private void setHasPDFDataView(String path) {
        uploadSignIcon.setImageResource(R.mipmap.pic_uploaded_pdf);
        int positon_x = path.lastIndexOf(File.separator);
        pdfFileName = path.substring(positon_x + 1, path.length());
        tvPdfName.setText(pdfFileName);
        tvDelete.setText("删除");
    }

    public void showViewByGetPath(String pdfFileName) {
        if (!StringUtils.isEmpty(pdfFileName) && pdfFileName.endsWith(".pdf")) {
//            localPdfPath = path;
            setHasPDFDataView(pdfFileName);
//            checkFileAndUpload();
        } else {
            uploadSignIcon.setImageResource(R.mipmap.pic_unupload_pdf);
            tvPdfName.setText("点击上传文件");
            tvDelete.setText("仅支持PDF文件");
            ToastShowUtils.showFailedToast("请选择PDF文件上传！");
            return;
        }
    }

    /**
     * 检测手动填写的报告链接是否是有效地址
     */
    private void checkUrlValid(){
        new Thread() {
            public void run() {
                try {
                    URL url = new URL(reportPcUrl);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setUseCaches(false);
                    conn.setRequestMethod("HEAD");
                    conn.setInstanceFollowRedirects(true);
                    conn.setConnectTimeout(4000);
                    conn.setReadTimeout(4000);
                    int responseCode = conn.getResponseCode();
                    Log.e("chj","response = " + responseCode);
                    if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_MOVED_PERM ||
                            responseCode == HttpURLConnection.HTTP_MOVED_TEMP || responseCode == HttpURLConnection.HTTP_NOT_MODIFIED) {
                        uploadPicsAndPDF();
                        return;
                    } else {
                        mainHandler.post(() -> {
                            clickUrlRadio();
                            ToastShowUtils.showFailedToast("填写地址无效，请填写正确的报告地址！");
                            return;
                        });
                    }

                } catch (Exception e) {
                    Log.e("chj","Exception");
                    Log.e("chj","Exception = " + e.toString());
                    mainHandler.post(() -> {
                        clickUrlRadio();
                        ToastShowUtils.showFailedToast("填写地址无效，请填写正确的报告地址！");
                        return;
                    });
                    e.printStackTrace();

                }
            }

        }.start();
    }


    /**
     * 校验文件是否已经存在服务器上，没有再上传
     */
    private void checkFileAndUpload() {
//        new Thread() {
//            public void run() {
//                try {
//                    URL url = new URL(SCAppConfig.IMG_URL + uploadHalfPDFPath());
//                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//                    conn.setUseCaches(false);
//                    conn.setRequestMethod("HEAD");
//                    conn.setInstanceFollowRedirects(true);
//                    conn.setConnectTimeout(2000);
//                    conn.setReadTimeout(2000);
//                    Log.e("chj","conn.getResponseCode() = " + conn.getResponseCode());
//                    if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
//                        detectionReportPdf = uploadHalfPDFPath();
//                        uploadMaintenanceReport();
//                        return;
//                    } else {
//                        mainHandler.post(() -> {
//                            upLoadToOSS(localPdfPath);
//                        });
//                    }
//                } catch (Exception e) {
//                    e.printStackTrace();
//                    mainHandler.post(() -> {
//                        upLoadToOSS(localPdfPath);
//                    });
//                }
//            }
//
//        }.start();
        upLoadToOSS(localPdfPath);
    }

    private void upLoadToOSS(String path) {
        pdfPaths.add(path);
        uploadType = 1;

        HttpHelper.getInstance().appendUrl(HttpUrl.OSS_AUTH)
                .get(new HttpCallBack<SCAccessAuthResponse>(this) {
                    @Override
                    public void onSuccessed(SCAccessAuthResponse result) {
                        SCAccessAuthResponse auth = result.getData();
                        //2.上传图片
                        if (proDialog == null) {
                            proDialog = new ProgressDialog(UploadDetectionActivity.this);
                            proDialog.setMessage("正在上传报告");
                            proDialog.setCanceledOnTouchOutside(false);
                        }
                        proDialog.show();

                        MultiImagesUploadManager.MultiImagesUploadCallback callback =
                                new MultiImagesUploadManager.MultiImagesUploadCallback() {
                                    @Override
                                    public void onSuccess(List<PutObjectRequest> requests) {
                                        if (requests != null && requests.size() > 0) {
                                            if (uploadType == 1) {
                                                detectionReportPdf = /*"/" + */requests.get(0).getObjectKey();
                                                Log.e("chj", "<<<<< path = " + detectionReportPdf);
                                                uploadMaintenanceReport();
                                            }
                                        }
                                        proDialog.dismiss();
                                        ToastShowUtils.showSuccessToast("上传成功");

                                    }

                                    @Override
                                    public void onFailure(List<PutObjectRequest> requests) {
                                        ToastShowUtils.showFailedToast("上传失败");
                                        proDialog.dismiss();
                                    }
                                };

                        if (uploadType == 1) {
                            new MultiImagesUploadManager().startUploadPDFByUri(localPdfUri, callback,
                                    auth.getAccessKeyId(), auth.getAccessKeySecret(), auth.getSecurityToken(),
                                    SCAppConfig.OSS_PDF_TESTREPORT);
                        }
                    }

                    @Override
                    public void onFailured(String errorCode, String errMsg) {

                    }
                });

    }

    /**
     * 加载图片
     */
    private void loadAdapter() {
        final SCCarEditUploadPicAdapter adapter = new SCCarEditUploadPicAdapter(
                this, carPictures, maxSize, true);
        gvPics.setAdapter(adapter);
        adapter.setListener(new SCCarEditUploadPicAdapter.deleteCallBackListener() {
            @Override
            public void delete(int index) {
                carPictures.remove(index);
                adapter.notifyDataSetChanged();
            }
        });
    }

    private void gotoSelectFile(){
        if (localPdfUri != null || !StringUtils.isEmpty(detectionReportPdf)) {
            Bundle bundle = new Bundle();
            if (!StringUtils.isEmpty(detectionReportPdf)) {
                bundle.putString("netUrl", detectionReportPdf);
                bundle.putBoolean("showShare", false);
            } else if (localPdfUri != null) {
                bundle.putParcelable("localPath", localPdfUri);
            }
            Intent pdfIntent = new Intent(this, PdfPreviewActivity.class);
            pdfIntent.putExtras(bundle);
            startActivity(pdfIntent);
//            startFragment(SCCarEditUploadDetectionFragment.this, SCPDFPreviewFragment.class, bundle);
        } else {
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
//            intent.setType("*/*");
            intent.setType("application/pdf");
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            startActivityForResult(intent, REQUEST_CODE_FILE);
        }
    }


    private void permissionGranted() {
        int type = gvPics.getAdapter().getItemViewType(picIndex);
        if (SCCarEditUploadPicAdapter.TYPE_CAMERA == type) {
            PhotoPickerIntent intent = new PhotoPickerIntent(this);

            intent.setSelectModel(SelectModel.MULTI);
            intent.setShowCarema(true); // 是否显示拍照
            intent.setMaxTotal(maxSize); // 最多选择照片数量，默认为6
            intent.setSelectedPaths(carPictures); // 已选中的照片地址， 用于回显选中状态
            startActivityForResult(intent, REQUEST_CODE_CAMERA);
        } else {
            PhotoPreviewIntent intent = new PhotoPreviewIntent(this);
            intent.setCurrentItem(picIndex);
            intent.setPhotoPaths(carPictures);
            intent.setShowMainPic(false);
            startActivityForResult(intent, REQUEST_CODE_PREVIEW);
        }
    }

    /**
     * 维保报告上传
     */
    private void uploadMaintenanceReport() {
        //发车 或 编辑进入
        Intent intent = new Intent();
        intent.putExtra("detectionReportPic", String.valueOf(urlSB));
        intent.putExtra("detectionReportUrl", reportPcUrl);
        if (!StringUtils.isEmpty(detectionReportPdf)) {
            if (!detectionReportPdf.contains("img.shuaiche.com")) {
                detectionReportPdf = SCAppConfig.IMG_URL + detectionReportPdf;
            }
            intent.putExtra("detectionReportPdf", detectionReportPdf);
        }
        Log.e("chj", "回传的PDF链接 <<<<< detectionReportPdf = " + detectionReportPdf);

        setResult(Activity.RESULT_OK,intent);
        finish();
//        finishActivity(Activity.RESULT_OK, intent);

    }

    private ProgressDialog proDialog; //上传进度条


    private String getMD5String() {
        return FileUtils.getFileMD5(new File(localPdfPath));
    }

    private String uploadHalfPDFPath() {
        return new MultiImagesUploadManager().getPDFPathPre(SCAppConfig.OSS_PDF_TESTREPORT) +
                getMD5String() + ".pdf";
    }



    @OnMPermissionGranted(BASIC_PERMISSION_REQUEST_CODE_FOR_CAMERA)
    public void onBasicPermissionSuccess() {
        permissionGranted();
    }

    @OnMPermissionGranted(BASIC_PERMISSION_REQUEST_CODE_FOR_FILE)
    public void onBasicSuccess(){
        gotoSelectFile();
    }

    @OnMPermissionDenied(BASIC_PERMISSION_REQUEST_CODE_FOR_CAMERA)
    @OnMPermissionNeverAskAgain(BASIC_PERMISSION_REQUEST_CODE_FOR_CAMERA)

    public void onBasicPermissionFailed() {
        ToastShowUtils.showTipToast("请先赋予app拥有该权限");
    }

    @OnMPermissionDenied(BASIC_PERMISSION_REQUEST_CODE_FOR_FILE)
    @OnMPermissionNeverAskAgain(BASIC_PERMISSION_REQUEST_CODE_FOR_FILE)
    public void onBasicFailed() {
        ToastShowUtils.showTipToast("请先赋予app拥有该权限");
    }


}